package com.rech.xbexpress3;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.rech.adapter.AddressAdapter;
import com.rech.adapter.LogisticAdapter;
import com.rech.adapter.adapterInterface.OnItemClickListener;
import com.rech.dialog.CustomDialog;
import com.rech.module.AddressModule;
import com.rech.module.LogisticModule;
import com.rech.scannergun.ScannerGunManager;
import com.rech.utils.OtherUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

/**
 * 现场寄件下单和微信寄件码寄件信息填写页
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class Jj3NewActivity extends AppCompatActivity {
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */
    private static final boolean AUTO_HIDE = true;
    private int mBoxType = 0;
    private String ljm = "";
    private String sjr;
    private String kdysj;
    private String urlImage;
    String boxValue = "[{}]";
    private TextView djs ;
    private Button tv_cabinet ;
    private Button tv_package ;
    private Timer countTimer;
    EditText kdysj_ctrl; //此处为收件人地址
    //EditText ljm_ctrl;
    //EditText sjr_ctrl;
    private String resCur;
    private Vector<Pair<String,String> > vec;
    ImageView jj3_cx_img;
    ImageView jj3_x_img;
    ImageView jj3_z_img;
    ImageView jj3_d_img;
    ImageView jj3_cd_img;
    private int jjcount = 300;
    private RelativeLayout rl_jjr;
    private RelativeLayout rl_sjr;
    private boolean isFromWX = false;
    private TextView tv_logic_name;

    private long jj3_clicktime = 0;

    public static final long TIME_INTERVAL = 2000L;
    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;
    private final Handler mHideHandler = new Handler();

    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar


        }
    };
    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            // Delayed display of UI elements
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
        }
    };
    private boolean mVisible;
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };
    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };
    private List<LogisticModule> logisticModule = new ArrayList<>();
    private String wl_id = "";
    private String kdy_id = "";
    //private Button btn_jjr_address;
    //private Button btn_sjr_address;
    private CustomDialog commitDialog;
    private Button btn_confirm;
    private AddressAdapter addressAdapter;
    private List<AddressModule> addressModules = new ArrayList<>();
    EditText jj3_jjr_address; //寄件人地址
    String sjh = "";
    String type = "1";
    String jj_orderId = "";
    private boolean isRequire;
    private LinearLayout boxtype_group;
    private LinearLayout packagetype_group;
    private RelativeLayout rl_choose_logic;
    private ImageView img_logic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isFromWX = getIntent().getBooleanExtra("isFromWX", false);
        SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
        String orientation = sharedPreferences.getString("Orientation","");
        sjh = sharedPreferences.getString("jj_sjh","");
        if (orientation.equals("landscape")) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        setContentView(R.layout.activity_jj3_new);
        jj3_jjr_address = (EditText) findViewById(R.id.jj3_jjr_address);
        boxtype_group = (LinearLayout) findViewById(R.id.boxtype_group);
        packagetype_group = (LinearLayout) findViewById(R.id.packagetype_group);
        tv_logic_name = (TextView)findViewById(R.id.tv_logic_name);
        img_logic = (ImageView)findViewById(R.id.img_logic);
        rl_choose_logic = (RelativeLayout) findViewById(R.id.rl_choose_logic);
        rl_choose_logic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null != logisticModule && logisticModule.size() > 0) {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("logisticModule", (Serializable) logisticModule);
                    intent.putExtras(bundle);
                    intent.setClass(Jj3NewActivity.this,ChooseLogicActivity.class);
                    //setResult(1009, intent);

                    startActivityForResult(intent, 1);
                } else {
                    Toast.makeText(Jj3NewActivity.this, "获取快递公司失败，请稍后重试", Toast.LENGTH_SHORT).show();
                    Exit();
                    finish();
                }
            }
        });

        //btn_sjr_address = (Button) findViewById(R.id.btn_sjr_address);
        //btn_jjr_address = (Button) findViewById(R.id.btn_jjr_address);
        //eventbus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        vec = new Vector<Pair<String,String>>(1, 1);
        mVisible = true;getSupportActionBar().hide();
        djs = findViewById(R.id.djs);

        tv_cabinet = findViewById(R.id.tv_cabinet);
        tv_cabinet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_package.setBackgroundResource(R.drawable.bg_gray_right_5);
                tv_cabinet.setBackgroundResource(R.drawable.bg_blue_left_5);
                tv_cabinet.setTextColor(getResources().getColor(R.color.yellow));
                tv_package.setTextColor(getResources().getColor(R.color.white));
                boxtype_group.setVisibility(View.VISIBLE);
                packagetype_group.setVisibility(View.INVISIBLE);
            }
        });
        tv_package = findViewById(R.id.tv_package);
        tv_package.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv_package.setBackgroundResource(R.drawable.bg_blue_right_5);
                tv_cabinet.setBackgroundResource(R.drawable.bg_gray_left_5);
                tv_cabinet.setTextColor(getResources().getColor(R.color.white));
                tv_package.setTextColor(getResources().getColor(R.color.yellow));
                boxtype_group.setVisibility(View.INVISIBLE);
                packagetype_group.setVisibility(View.VISIBLE);
            }
        });

        //boxValue  =  sharedPreferences.getString("jj_boxvalue", "[{}]");

        kdysj_ctrl = findViewById(R.id.jj3_kdysj);

        if (sharedPreferences.getString("jj_jjr_address", "").equals("") && !isFromWX) {
            isRequire = true;
            type = "1";
            new FetchAddress(sjh, type).execute();
        } else {
            jj3_jjr_address.setText(sharedPreferences.getString("jj_jjr_address", ""));
        }


        kdysj_ctrl.setText(sharedPreferences.getString("jj_sjr_address", ""));
        if (isFromWX) {
            jj_orderId = sharedPreferences.getString("jj_wx_orderId", "");
            jj3_jjr_address.setEnabled(false);
            jj3_jjr_address.setFocusable(false);
            jj3_jjr_address.setFocusableInTouchMode(false);

            kdysj_ctrl.setEnabled(false);
            kdysj_ctrl.setFocusable(false);
            kdysj_ctrl.setFocusableInTouchMode(false);

            //btn_jjr_address.setVisibility(View.GONE);
            //btn_sjr_address.setVisibility(View.GONE);
        }
        new FetchGetBoxStateTask().execute();

        TextView jj3_qx = (TextView) findViewById(R.id.tv_back);
        jj3_qx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long nowTime = System.currentTimeMillis();

                if (nowTime - jj3_clicktime > TIME_INTERVAL) {
                    jj3_clicktime = nowTime;

                    SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                    editor.putString("jj_sjr_address","");
                    editor.putString("jj_jjr_address","");
                    editor.putString("kdy_id","");
                    editor.putString("wl_id","");
                    editor.apply();

                    Intent intent = new Intent();
                    setResult(1001, intent);
                    Exit();
                    finish();
                }
            }
        });



        Button jj3_qd = (Button) findViewById(R.id.btn_commit);
        jj3_qd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long nowTime = System.currentTimeMillis();

                if (nowTime - jj3_clicktime > TIME_INTERVAL) {
                    jj3_clicktime = nowTime;
                    if (wl_id.equals("")) {
                        Toast.makeText(Jj3NewActivity.this, "请选择快递公司", Toast.LENGTH_SHORT).show();
                        return ;
                    }
                    if(mBoxType == 0) {
                        //Toast.makeText(Jj3NewActivity.this, "请选择格子类型", Toast.LENGTH_SHORT).show();
                        showNoTypeDialog();
                        return ;
                    }

                    /*String jj3_jjr_addressj_str = jj3_jjr_address.getText().toString();
                    String jj3_kdysj_str = kdysj_ctrl.getText().toString();

                    if(jj3_jjr_addressj_str.length() < 1)
                    {
                        Toast.makeText(Jj3NewActivity.this, "请输入寄件人地址", Toast.LENGTH_SHORT).show();
                        return ;
                    }
                    if(jj3_kdysj_str.length() < 1)
                    {
                        Toast.makeText(Jj3NewActivity.this, "请输入收件人地址", Toast.LENGTH_SHORT).show();
                        return ;
                    }*/
                    SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                    editor.putString("jj_sjr_address",kdysj_ctrl.getText().toString().trim());
                    editor.putString("jj_jjr_address",jj3_jjr_address.getText().toString().trim());
                    //editor.putString("jj_ljm",ljm);
                    editor.putString("jj_sjr",sjr);
                    editor.putString("kdy_id",kdy_id);
                    editor.putString("wl_id",wl_id);
                    editor.apply();

                    //如果是重选格子，则不需要再次进行人脸识别
                    SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
                    boolean isReChoose = sharedPreferences.getBoolean("isReChoose",false);
                    if (isReChoose) {
                        new FetchIO485GridTaskForJJ(mBoxType).execute();
                    } else {
                        Intent intent = new Intent();
                        intent.putExtra("isFromWX", isFromWX?1:0);
                        intent.putExtra("mBoxType", mBoxType);
                        setResult(1008, intent);
                        Exit();
                        finish();
                    }
                }
            }
        });

        countTimer=new Timer();
        countTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                jjcount--;
                Message message = new Message();
                message.what=20000;
                EventBus.getDefault().post(message);
                if(jjcount < 1){
                    //OtherUtil.restartApplication(Jj3NewActivity.this);
                    SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                    editor.putString("jj_sjr_address","");
                    editor.putString("jj_jjr_address","");
                    editor.putString("kdy_id","");
                    editor.putString("wl_id","");
                    editor.apply();

                    Exit();
                    finish();
                }
            }
        },0,1000);

        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        new FetchLogistics().execute();

        /*btn_jjr_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                type = "1";
                new FetchAddress(sjh, type).execute();
            }
        });
        btn_sjr_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                type = "2";
                new FetchAddress(sjh, type).execute();
            }
        });*/

        TextView tv_version = findViewById(R.id.tv_version);
        TextView tv_waiter = findViewById(R.id.tv_waiter);
        try {
            tv_version.setText("v" + OtherUtil.getVersion(this));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String phone = sharedPreferences.getString("CabinetType_phone","");
        tv_waiter.setText("客服电话:" + phone);
    }

    private void showNoTypeDialog() {
        View view = View.inflate(this, R.layout.dialog_no_type, null);
        initDialogView(view);
        commitDialog = new CustomDialog(this, OtherUtil.dp2px(500), OtherUtil.dp2px(560),
                view, R.style.CustomDialog);
        commitDialog.show();
    }

    private void initDialogView(View view) {
        btn_confirm = view.findViewById(R.id.btn_confirm);

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeDialog();
            }
        });
    }

    private void closeDialog() {
        if (commitDialog != null && commitDialog.isShowing()) {
            commitDialog.dismiss();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode > 0){
            try{
                Message message = new Message();
                message.what=resultCode;
                if (resultCode == 1010) {
                    wl_id = data.getStringExtra("wl_id");
                    for(int i=0; i<logisticModule.size(); i++){
                        if (wl_id.equals(logisticModule.get(i).getId())) {
                            logisticModule.get(i).setChecked(true);
                            kdy_id = logisticModule.get(i).getAdminid();
                            tv_logic_name.setText(logisticModule.get(i).getName());
                            if (logisticModule.get(i).getName().contains("申通")) {
                                img_logic.setImageResource(R.mipmap.img_logic_shentong);
                            } else if (logisticModule.get(i).getName().contains("中通")) {
                                img_logic.setImageResource(R.mipmap.img_logic_zhongtong);
                            } else if (logisticModule.get(i).getName().contains("韵达")) {
                                img_logic.setImageResource(R.mipmap.img_logic_yunda);
                            } else if (logisticModule.get(i).getName().contains("天天")) {
                                img_logic.setImageResource(R.mipmap.img_logic_tiantian);
                            } else if (logisticModule.get(i).getName().contains("百世")) {
                                img_logic.setImageResource(R.mipmap.img_logic_baishi);
                            } else if (logisticModule.get(i).getName().contains("圆通")) {
                                img_logic.setImageResource(R.mipmap.img_logic_yuantong);
                            } else if (logisticModule.get(i).getName().contains("天天")) {
                                img_logic.setImageResource(R.mipmap.img_logic_tiantian);
                            } else {
                                img_logic.setImageResource(R.mipmap.img_logic_rabbit);
                            }
                        } else {
                            logisticModule.get(i).setChecked(false);
                        }
                    }
                }
            }catch (Exception e) {

            }

        }
    }

    private void showRegisterDialog() {
        View view = View.inflate(this, R.layout.dialog_address, null);
        initregisterDialogView(view);
        commitDialog = new CustomDialog(this, OtherUtil.dp2px(480), OtherUtil.dp2px(640),
                view, R.style.CustomDialog);
        commitDialog.show();
    }

    private void initregisterDialogView(View view) {
        RecyclerView rvData = (RecyclerView) view.findViewById(R.id.rv_content_address);
        LinearLayoutManager manager = new LinearLayoutManager(view.getContext());
        rvData.setLayoutManager(manager);
        addressAdapter = new AddressAdapter(view.getContext(), addressModules);
        rvData.setAdapter(addressAdapter);

        addressAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                closeDialog();
                if (!type.equals("1")) {
                    kdysj_ctrl.setText(addressModules.get(position).getDetail());
                } else {
                    jj3_jjr_address.setText(addressModules.get(position).getDetail());
                }
            }
        });
    }

    private void Exit(){
        countTimer.cancel();
        EventBus.getDefault().unregister(this);
    }
    @Override
    protected void onDestroy() {

        super.onDestroy();
    }
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mVisible = false;

        // Schedule a runnable to remove the status and navigation bar after a delay
//        mHideHandler.removeCallbacks(mShowPart2Runnable);
//        mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
    }

    @SuppressLint("InlinedApi")
    private void show() {
        // Show the system bar
        mVisible = true;

        // Schedule a runnable to display UI elements after a delay
//        mHideHandler.removeCallbacks(mHidePart2Runnable);
//        mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
    }

    /**
     * Schedules a call to hide() in delay milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }
    private void handleBoxType(Object obj){
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                JSONArray orders = result.getJSONArray("data");
                boxValue = orders.toString();
                boolean hasBox = false;
                for(int i=0; i<orders.length(); i++){
                    JSONObject jsonObject1 = orders.getJSONObject(i);
                    String itemType = jsonObject1.get("type").toString();
                    if(itemType.equals("1")) {
                        hasBox = true;

                        boxtype_group.setVisibility(View.VISIBLE);
                        String itemId = jsonObject1.get("id").toString();
                        String itemName = jsonObject1.get("name").toString();
                        final int count = Integer.parseInt(jsonObject1.get("count").toString());

                        final String nameId = "jj3_name"+String.valueOf(i+1);
                        final String layoutId = "jj3_box"+String.valueOf(i+1);
                        ((TextView)findViewById(OtherUtil.getResId(nameId,R.id.class))).setText(itemName + "\n" + count);
                        vec.add(new Pair<String, String>(itemId, nameId));
                        ((LinearLayout) findViewById(OtherUtil.getResId(layoutId, R.id.class))).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (count == 0) {
                                    return;
                                }
                                ((TextView) findViewById(OtherUtil.getResId(nameId, R.id.class))).setBackgroundResource(R.drawable.img_bg_select);
                                ((TextView) findViewById(OtherUtil.getResId(nameId, R.id.class))).setTextColor(getResources().getColor(R.color.yellow));
                                resCur = nameId;
                                ChoiceBox();
                            }
                        });
                        findViewById(OtherUtil.getResId(layoutId,R.id.class)).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.WRAP_CONTENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
                    }else{
                        String itemId = jsonObject1.get("id").toString();
                        String itemName = jsonObject1.get("name").toString();
                        final int count = Integer.parseInt(jsonObject1.get("count").toString());

                        final String nameId = "package_name"+String.valueOf(i+1);
                        final String layoutId = "jj3_package"+String.valueOf(i+1);
                        ((TextView)findViewById(OtherUtil.getResId(nameId,R.id.class))).setText(itemName + "\n" + count);
                        vec.add(new Pair<String, String>(itemId,nameId));
                        ((LinearLayout)findViewById(OtherUtil.getResId(layoutId,R.id.class))).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (count == 0) {
                                    return;
                                }
                                ((TextView)findViewById(OtherUtil.getResId(nameId,R.id.class))).setBackgroundResource(R.drawable.img_bg_select);
                                ((TextView) findViewById(OtherUtil.getResId(nameId, R.id.class))).setTextColor(getResources().getColor(R.color.yellow));
                                resCur = nameId;
                                ChoiceBox();
                            }
                        });
                        findViewById(OtherUtil.getResId(layoutId,R.id.class)).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.WRAP_CONTENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
                    }

                    if (!hasBox) {
                        packagetype_group.setVisibility(View.VISIBLE);
                    }
                }
            }
        }
        catch (Exception e) {
            Log.d("Grid", e.toString());
        }

    }
    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message){
        Intent intent = new Intent();
        switch(message.what){
            case 20000:
                handleDJS();
                break;
            case 10127:
                handleLogisticsTask(message.obj);
                break;
            case 10128:
                Toast.makeText(Jj3NewActivity.this, "获取快递公司失败，请稍后重试", Toast.LENGTH_SHORT).show();
                Exit();
                finish();
                break;
            case 10129:
                handleAddressTask(message.obj);
                break;
            case 10130:
                Toast.makeText(Jj3NewActivity.this, "获取地址失败", Toast.LENGTH_SHORT).show();
                break;
            case 10120:
                handleGetIO485Task(message.obj);
                break;
            case 10121:
                Toast.makeText(Jj3NewActivity.this, "获取柜子状态失败，请稍后重试", Toast.LENGTH_SHORT).show();
                Exit();
                finish();
                break;
            case 20101:
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();
                editor.putBoolean("isReChoose",false);
                editor.apply();
                intent.putExtra("isFromWX", true);
                setResult(1005, intent);
                Exit();
                finish();
                break;
            case 10106:
                handleBoxType(message.obj);
                break;

        }
    }

    private void handleAddressTask(Object obj) {
        addressModules.clear();
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                JSONArray orders = result.getJSONArray("data");
                for(int i=0; i<orders.length(); i++){
                    JSONObject jsonObject1 = orders.getJSONObject(i);
                    AddressModule addressModule = new AddressModule();
                    addressModule.setDetail(jsonObject1.get("detail").toString());
                    addressModules.add(addressModule);
                }

                if (null != addressModules && addressModules.size() > 0 && isRequire) {
                    jj3_jjr_address.setText(addressModules.get(0).getDetail());
                    isRequire = false;
                } else {
                    showRegisterDialog();
                    addressAdapter.notifyDataSetChanged();
                }
            } else {
                Toast.makeText(Jj3NewActivity.this, "暂无常用地址", Toast.LENGTH_SHORT).show();
            }
        }
        catch (Exception e){
        }
    }

    private void handleLogisticsTask(Object obj) {
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                JSONArray orders = result.getJSONArray("data");
                SharedPreferences sharedPreferences = getSharedPreferences("xbbox", Context.MODE_PRIVATE);
                String id = sharedPreferences.getString("wl_id","");
                //kdy_id = sharedPreferences.getString("kdy_id","");
                //wl_id = sharedPreferences.getString("wl_id","");
                for(int i=0; i<orders.length(); i++){
                    JSONObject jsonObject1 = orders.getJSONObject(i);
                    LogisticModule logisticModuleNew = new LogisticModule();
                    logisticModuleNew.setName(jsonObject1.get("name").toString());
                    logisticModuleNew.setAdminid(jsonObject1.get("adminid").toString());
                    logisticModuleNew.setId(jsonObject1.get("id").toString());
                    /*if (id.equals(jsonObject1.get("id").toString())) {
                        logisticModuleNew.setChecked(true);
                        wl_id = jsonObject1.get("id").toString();
                        kdy_id = jsonObject1.get("adminid").toString();
                        tv_logic_name.setText(jsonObject1.get("name").toString());
                    }*/
                    logisticModule.add(logisticModuleNew);
                }

                if (null == id || id.equals("")) {
                    tv_logic_name.setText(logisticModule.get(0).getName());
                    if (logisticModule.get(0).getName().contains("申通")) {
                        img_logic.setImageResource(R.mipmap.img_logic_shentong);
                    } else if (logisticModule.get(0).getName().contains("中通")) {
                        img_logic.setImageResource(R.mipmap.img_logic_zhongtong);
                    } else if (logisticModule.get(0).getName().contains("韵达")) {
                        img_logic.setImageResource(R.mipmap.img_logic_yunda);
                    } else if (logisticModule.get(0).getName().contains("天天")) {
                        img_logic.setImageResource(R.mipmap.img_logic_tiantian);
                    } else if (logisticModule.get(0).getName().contains("百世")) {
                        img_logic.setImageResource(R.mipmap.img_logic_baishi);
                    } else if (logisticModule.get(0).getName().contains("圆通")) {
                        img_logic.setImageResource(R.mipmap.img_logic_yuantong);
                    } else if (logisticModule.get(0).getName().contains("天天")) {
                        img_logic.setImageResource(R.mipmap.img_logic_tiantian);
                    } else {
                        img_logic.setImageResource(R.mipmap.img_logic_rabbit);
                    }
                    wl_id = logisticModule.get(0).getId();
                    kdy_id = logisticModule.get(0).getAdminid();
                    logisticModule.get(0).setChecked(true);
                } else {
                    for(int i=0; i<logisticModule.size(); i++){
                        if (id.equals(logisticModule.get(i).getId())) {
                            logisticModule.get(i).setChecked(true);
                            wl_id = logisticModule.get(i).getId();
                            kdy_id = logisticModule.get(i).getAdminid();
                            tv_logic_name.setText(logisticModule.get(i).getName());
                            if (logisticModule.get(i).getName().contains("申通")) {
                                img_logic.setImageResource(R.mipmap.img_logic_shentong);
                            } else if (logisticModule.get(i).getName().contains("中通")) {
                                img_logic.setImageResource(R.mipmap.img_logic_zhongtong);
                            } else if (logisticModule.get(i).getName().contains("韵达")) {
                                img_logic.setImageResource(R.mipmap.img_logic_yunda);
                            } else if (logisticModule.get(i).getName().contains("天天")) {
                                img_logic.setImageResource(R.mipmap.img_logic_tiantian);
                            } else if (logisticModule.get(i).getName().contains("百世")) {
                                img_logic.setImageResource(R.mipmap.img_logic_baishi);
                            } else if (logisticModule.get(i).getName().contains("圆通")) {
                                img_logic.setImageResource(R.mipmap.img_logic_yuantong);
                            } else if (logisticModule.get(i).getName().contains("天天")) {
                                img_logic.setImageResource(R.mipmap.img_logic_tiantian);
                            } else {
                                img_logic.setImageResource(R.mipmap.img_logic_rabbit);
                            }
                        } else {
                            logisticModule.get(i).setChecked(false);
                        }
                    }
                }
            }
        }
        catch (Exception e){
        }
    }

    public void handleOpenGridTask(Object obj) {
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                //String jj_gridtype = result.getJSONObject("data").getString("gridtype");
                String jj_gridnum = result.getJSONObject("data").getString("gridNum");
                String jj_io = result.getJSONObject("data").getString("IO");
                String jj_485 = result.getJSONObject("data").getString("485");
                String jj_cabinetgridid = result.getJSONObject("data").getString("cabinetGridId");
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();

                editor.putString("jj_kdysj",kdysj);
                //editor.putString("jj_ljm",ljm);
                editor.putString("jj_sjr",sjr);
                editor.putString("jj_cabinetgridid",jj_cabinetgridid);
                //editor.putString("jj_gridtype",jj_gridtype);
                editor.putString("jj_gridnum",jj_gridnum);
                editor.putString("jj_io",jj_io);
                editor.putString("jj_485",jj_485);
                editor.apply();
                OtherUtil.OpenVoice2(this);
                Intent intent = new Intent();
                setResult(1005, intent);
                Exit();
                finish();
            }
        }
        catch (Exception e){
            Log.d("handleSendGridTask",e.toString());
        }
    }
    private void handleGetIO485Task(Object obj){
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                SharedPreferences.Editor editor = getSharedPreferences("xbbox",MODE_PRIVATE).edit();

                editor.putString("reopen",obj.toString());
                editor.putString("jj_gridnum",result.getJSONObject("data").getString("gridNum"));
                editor.putString("jj_cabinetgridid",result.getJSONObject("data").getString("cabinetGridId"));
                editor.apply();

                new FetchOpenLocalGridTaskv2ForJJ(obj.toString()).execute();

            }
        }
        catch (Exception e){
            Log.d("handleSendGridTask",e.toString());
        }
    }
    private void handleDJS(){
        djs.setText(String.valueOf(jjcount));
    }

    private void ChoiceBox(){
        for(int i=0;i<vec.size();i++){
            String layoutId = vec.get(i).second;
            if(layoutId.equals(resCur)){
                mBoxType = Integer.parseInt(vec.get(i).first);
                //((TextView)findViewById(OtherUtil.getResId(layoutId,R.id.class))).setBackgroundColor(getResources().getColor(R.color.button_blue));

            }else{
                ((TextView)findViewById(OtherUtil.getResId(layoutId,R.id.class))).setBackgroundResource(R.drawable.bg_blue_button_5);
                ((TextView) findViewById(OtherUtil.getResId(layoutId, R.id.class))).setTextColor(getResources().getColor(R.color.white));
            }
        }
    }

}
